import { ref, watch } from 'vue'

const THEME_KEY = 'theme'
const DARK_THEME = 'dark'
const LIGHT_THEME = 'light'

export function useTheme() {
  const isDark = ref(localStorage.getItem(THEME_KEY) === DARK_THEME)

  const setTheme = (dark: boolean) => {
    isDark.value = dark
    localStorage.setItem(THEME_KEY, dark ? DARK_THEME : LIGHT_THEME)
    document.documentElement.classList.toggle(DARK_THEME, dark)
  }

  const toggleTheme = () => {
    setTheme(!isDark.value)
  }

  // 监听系统主题变化
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
  const handleThemeChange = (e: MediaQueryListEvent) => {
    if (!localStorage.getItem(THEME_KEY)) {
      setTheme(e.matches)
    }
  }

  mediaQuery.addEventListener('change', handleThemeChange)

  // 初始化主题
  if (!localStorage.getItem(THEME_KEY)) {
    setTheme(mediaQuery.matches)
  } else {
    setTheme(isDark.value)
  }

  return {
    isDark,
    toggleTheme
  }
} 